package yzx.fileutil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import yzx.fileutil.fragment.FileCopyFragment;
import yzx.fileutil.fragment.FileExchangeFragment;
import yzx.fileutil.util.ID;
import yzx.fileutil.util.Injector;

public class MainActivity extends AppCompatActivity {

    public static void launch(Context from){
        Intent intent = new Intent(from, MainActivity.class);
        from.startActivity(intent);
    }


    @ID(id=R.id.tabLayout)
    private TabLayout tabLayout;
    @ID(id=R.id.viewPager)
    private ViewPager viewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Injector.injectField(this);
        initView();
    }


    private final String[] titles = {"文件扩展名修改", "文件搬家"};
    private void initView(){
        clearFragmentOnTransition();
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            public Fragment getItem(int position) {
                switch (position){
                    case 0: return new FileExchangeFragment();
                    case 1: return new FileCopyFragment();
                    default: return null;
                }
            }
            public int getCount() {
                return titles.length;
            }
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });
        tabLayout.setupWithViewPager(viewPager);
    }
    /* 清除全部已经加入过事物的fragment */
    private void clearFragmentOnTransition(){
        FragmentManager fm = getSupportFragmentManager();
        if(fm.getFragments()==null||fm.getFragments().isEmpty())
            return ;
        FragmentTransaction transaction = fm.beginTransaction();
        for (Fragment fragment : fm.getFragments())
            transaction.remove(fragment);
        transaction.commitNow();
    }

}
